<template v-if="LOAD">
    <div class="chart-container-wrapper">
        <!-- 左侧三图 -->
        <div class="side-column left-side">
            <div class="chart-item">
                <BarChart title="人口统计" :x-axis-data="years" :series-data="population" x-axis-name="年份"
                    y-axis-name="人数/万" :y-axis-min="2450" />
            </div>
            <div class="chart-item">
                <LineChart title="出生率/死亡率趋势对比" :x-axis-data="years" :series-list="[{
                    name: '出生率', data: birthRate
                }, {
                    name: '死亡率', data: deathRate
                }]" x-axis-name="年份" y-axis-name="比率(%)" />
            </div>

            <div class="chart-item">
                <PieChart title="年龄组成" :series-data=AgeComposition
                    :colors="['#4dd3ff', '#73a6aa', '#bd6b9c', '#1061a3']" rose-type="radius" />
            </div>
        </div>

        <!-- 中间地图（固定在中央） -->
        <div class="center-column">
            <div class="map-container">
                <h3 class="chart-title">上海市行政区划图</h3>
                <div class="map-wrapper">
                    <div ref="chartContainer" class="chart-container"></div>
                </div>
            </div>
        </div>

        <!-- 右侧三图 -->
        <div class="side-column right-side">
            <div class="chart-item">
                <BarChart title="上海市GDP" :x-axis-data=years :series-data=GDP x-axis-name="年份" y-axis-name="万亿人民币" />
            </div>
            <div class="chart-item">
                <LineChart title="GDP增速" :x-axis-data="years" :series-list="[{
                    name: 'GDP增速', data: GDPGrowth, color: '#d65a8d'
                }]" x-axis-name="年份" y-axis-name="比率(%)" />
            </div>

            <div class="chart-item">
                <PieChart title="产业比例" :series-data=IndustryProportion :colors="['#4dffe7', '#4dd3ff', '#1061a3',]" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import request from '../../utils/request';
import PieChart from '../DataChart/PieChart.vue';
import BarChart from '../DataChart/BarChart.vue';
import LineChart from '../DataChart/LineChart.vue';
import { getShanghaiGDP, getShanghaiGDPGrowth, getShanghaiTotalPopulationProcessed, getShanghaiBirthDeathRate } from '../../apis/ShanghaiTotal';

const chartContainer = ref<HTMLElement | null>(null);
let myChart: echarts.ECharts | null = null;
//  子组件 向父组件 传递事件
const emit = defineEmits(['district-clicked']);
// 上海人口总数据相关
const years = ref<number[]>([]);
const population = ref<number[]>([]);

const loadPopulationData = async () => {
    try {
        const data = await getShanghaiTotalPopulationProcessed();
        years.value = data.map(item => item.year);
        population.value = data.map(item => item.people);
    } catch (error) {
        console.error('获取上海人口数据失败:', error);
    }
};
// 上海人口出生率和死亡率相关
const birthRate = ref<number[]>([]);
const deathRate = ref<number[]>([]);
const loadBirthDeathRateData = async () => {
    try {
        const data = await getShanghaiBirthDeathRate();
        years.value = data.map(item => item.year);
        birthRate.value = data.map(item => item.birthRate);
        deathRate.value = data.map(item => item.deathRate);
    } catch (error) {
        console.error('获取上海出生率和死亡率数据失败:', error);
    }
};
//上海GDP相关
const GDP = ref<number[]>([]);
const loadGDPData = async () => {
    try {
        const data = await getShanghaiGDP();
        years.value = data.map(item => item.year);
        GDP.value = data.map(item => item.gdp);

    } catch (error) {
        console.error('获取上海GDP数据失败:', error);
    }
};
//上海GDP增速相关
const GDPGrowth = ref<number[]>([]);
const loadGDPGrowthData = async () => {
    try {
        const data = await getShanghaiGDPGrowth();
        years.value = data.map(item => item.year);
        GDPGrowth.value = data.map(item => item.growthRate);

    } catch (error) {
        console.error('获取上海GDP增速数据失败:', error);
    }
};

// 上海人口年龄组成相关
const AgeComposition = ref<{ name: string; value: number }[]>([]);
AgeComposition.value = [
    { name: '17岁以下', value: 194.80 },
    { name: '18-34岁', value: 215.87 },
    { name: '35-59岁', value: 539.01 },
    { name: '60岁以上', value: 566.71 }
];
//三大产业比例相关
const IndustryProportion = ref<{ name: string; value: number }[]>([]);
IndustryProportion.value = [
    { name: '第一产业', value: 96.09 },
    { name: '第二产业', value: 11612.97 },
    { name: '第三产业', value: 35509.60 }
];
// 窗口大小调整处理
const handleResize = () => {
    if (myChart) {
        myChart.resize();
    }
};
const LOAD = ref(false)
onMounted(async () => {
    await Promise.all([
        loadPopulationData(),
        loadBirthDeathRateData(),
        loadGDPData(),
        loadGDPGrowthData()
    ]);
    LOAD.value = true

    if (!chartContainer.value) {
        console.error('chartContainer 元素未找到');
        return;
    }

    myChart = echarts.init(chartContainer.value);

    try {
        const response = await request.get('/api/shanghai-districts');
        echarts.registerMap('shanghai', response.data);

        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{b}'
            },
            series: [
                {
                    type: 'map',
                    center: [121.4737, 31.3],
                    map: 'shanghai',
                    roam: true,
                    zoom: 1,
                    scaleLimit: {
                        min: 0.8,
                        max: 20
                    },
                    label: {
                        show: true,
                        color: '#000',
                        fontSize: 12,
                    },
                    itemStyle: {
                        areaColor: '#e0f3f8',
                        borderColor: '#555',
                        borderWidth: 1,
                    },
                    emphasis: {
                        label: {
                            show: true,
                            color: '#333',
                        },
                        itemStyle: {
                            areaColor: '#bde3ef',
                        },
                    },
                    labelLayout: {
                        hideOverlap: true,
                        moveOverlap: 'shiftY'
                    }
                },
            ],
        };

        myChart.setOption(option);

        //点击切换不同的区

        // 当用户点击地图上的某个区（例如"浦东新区"）时：
        //ECharts 检测到点击事件，并触发你绑定的回调函数
        //回调函数获取被点击区域的名称（params.name）
        //调用 emit('district-clicked', districtName)。将事件和数据传递给父组件

        myChart.on('click', (params: any) => {
            const districtName = params.name; // 获取点击的区名
            // console.log(`点击了: ${districtName}`);
            emit('district-clicked', districtName); // 发送事件给父组件
        });


        window.addEventListener('resize', handleResize);
    } catch (error) {
        console.error('获取地图数据失败，请检查后端服务是否已启动并提供数据:', error);
    }
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
    if (myChart) {
        myChart.dispose();
    }
});
</script>

<style lang="scss" scoped>
.chart-container-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    width: 100%;
    height: 100%;
    gap: 20px;
    padding: 20px;
    box-sizing: border-box;

    // 三列布局
    .side-column {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 20px;
        min-width: 250px;

        &.left-side {
            order: 1;
        }

        &.right-side {
            order: 3;
        }
    }

    .center-column {
        flex: 1.5; // 中间更宽
        display: flex;
        flex-direction: column;
        align-items: center;
        order: 2;
        position: sticky;
        padding: 20px;
        top: 50%;
        transform: translateY(-50%);
        z-index: 10;
    }

    .chart-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        height: 100%;
    }

    .chart-title {
        text-align: center;
        font-weight: bold;
        font-size: 16px;
        margin-bottom: 15px;
        color: #333;
    }

    .map-container {
        margin-top: 25px;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .map-wrapper {
        width: 100%;
        height: 400px;
        border: 1px solid #ccc;
        border-radius: 4px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .chart-container {
        width: 100%;
        height: 100%;
    }

    // 图表组件容器样式
    .bar-chart-container,
    .line-chart-container,
    .pie-chart-container {
        width: 100%;
        height: 400px;
        border: 1px solid #ccc;
        border-radius: 4px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    // 响应式调整
    @media (max-width: 1200px) {
        .chart-container-wrapper {
            flex-direction: column;
        }

        .side-column,
        .center-column {
            width: 100%;
        }

        .chart-item {
            width: 100%;
        }
    }
}
</style>